Number of distinct islands¶
Time: O(MxN); Space: O(MxN); medium
Given a non-empty 2D array grid of 0’s and 1’s, an island is a group of 1’s (representing land) connected 4-directionally (horizontal or vertical). You may assume all four edges of the grid are surrounded by water.
Count the number of distinct islands. An island is considered to be the same as another if and only if one island has the same shape as another island (and not rotated or reflected).
Notice that:
11
1
and
1
11
are considered different island, because we do not consider reflection / rotation.
Constraint:
The length of each dimension in the given grid does not exceed 50.
Example 1:
Input: grid =
[
[1,1,0,0,1],
[1,0,0,0,0],
[1,1,0,0,1],
[0,1,0,1,1]
]
Output: 3
Example 2:
Input: grid =
[
[1,1,0,0,0],
[1,1,0,0,0],
[0,0,0,1,1],
[0,0,0,1,1]
]
Output: 1
[3]:
class Solution1(object):
"""
Time: O(M*N)
Space: O(M*N)
"""
def numDistinctIslands(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
directions = {'l':[-1, 0],
'r':[ 1, 0],
'u':[ 0, 1],
'd':[ 0, -1]
}
def dfs(i, j, grid, island):
if not (0 <= i < len(grid) and \
0 <= j < len(grid[0]) and \
grid[i][j] > 0):
return False
grid[i][j] *= -1
for k, v in directions.items():
island.append(k)
dfs(i+v[0], j+v[1], grid, island)
return True
islands = set()
for i in range(len(grid)):
for j in range(len(grid[0])):
island = []
if dfs(i, j, grid, island):
islands.add(''.join(island))
return len(islands)
[4]:
s = Solution1()
grid = [
[1,1,0,0,1],
[1,0,0,0,0],
[1,1,0,0,1],
[0,1,0,1,1]
]
assert s.numDistinctIslands(grid) == 3
grid = [
[1,1,0,0,0],
[1,1,0,0,0],
[0,0,0,1,1],
[0,0,0,1,1]
]
assert s.numDistinctIslands(grid) == 1